package top.yehot.cmmu.swagger.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.google.common.collect.Sets;

import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@EnableKnife4j
@Import(BeanValidatorPluginsConfiguration.class)
public class AppAutoConfiguration {
	
	@Autowired
	private SwaggerProperties sp;
	
	@Bean
    public Docket createRestApi() {
		if (!sp.getEnabled()) return null;
		
		return new Docket(DocumentationType.SWAGGER_2)
        		.produces(Sets.newHashSet("application/json"))
        		.consumes(Sets.newHashSet("application/json"))
        		.protocols(Sets.newHashSet("http", "https"))
                .apiInfo(apiInfo())
                .forCodeGeneration(true)
                .select()
                // 对所有api进行监控
//                .apis(RequestHandlerSelectors.any())
                // 监控指定包下的URL
                .apis(RequestHandlerSelectors.basePackage(sp.getAppInfo().getBasePackage()))
                // 不显示错误的接口地址
                .paths(PathSelectors.any())
                // 错误路径不监控
//                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build();
    }

	/**
     * 创建Swagger页面 信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
        		.title(sp.getAppInfo().getTitle())
        		.contact(new Contact(sp.getAppInfo().getContact(), "", sp.getAppInfo().getContactEmail()))
        		.version(sp.getAppInfo().getVersion())
                .license(sp.getAppInfo().getLicense())
                .licenseUrl(sp.getAppInfo().getLicenseUrl())
                .termsOfServiceUrl(sp.getAppInfo().getTermsOfServiceUrl())
                .description(sp.getAppInfo().getDescription())
                .build();
    }
	
}
